<?php

/**
 * Class Sitemap
 */
class Sitemap {

    /**
     * XML 命名空间
     *
     * @var string
     */
    public $xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";

    /**
     *
     * 要生成 URL 的列表
     *
     * @var array
     */
    public $urls = array();

    /**
     *
     * URL Item 的模板 <url>\r\n<loc>%s</loc>\r\n<changefreq>%s</changefreq>\r\n<lastmod>%s</lastmod>\r\n<priority>%s</priority>\r\n</url>
     * @var string
     */
    public $urlItemTpl = "<url>\r\n<loc>%s</loc>\r\n<priority>%s</priority>\r\n</url>";

    /**
     * 生成的 sitemap 文件名
     * @var string
     */
    public $filename = 'sitemap.xml';

    /**
     * 保存 sitemap 文件路径
     *
     * @var string
     */
    public $basePath;

    /**
     * @var array
     */
    private $_urls = array();

    public function __construct() {
        if (!$this->basePath) {
            $this->basePath = Yii::getPathOfAlias('webroot') . '/';
        }
    }

    public function init() {
        foreach ($this->urls as $url) {
            $frequency = $url['frequency'] ? $url['frequency'] : 'Always';
            $priority = $url['priority'] ? $url['priority'] : '0.2';
            unset($url['frequency']);
            unset($url['priority']);
            if (isset($url['model'])) {
                // 从模型中生成 URl
                $modelName = $url['model'];
                $criteria = $url['criteria'];
                $tpl = $url['url'];
                $urls = $this->createUrlsByModel($modelName, $criteria, $tpl, $frequency, $priority);
                $this->_urls = CMap::mergeArray($this->_urls, $urls);
            } else {
                // 自定义的 URL
                $this->_urls[] = array(
                    'url' => $url['url'],
                    'frequency' => $frequency,
                    'priority' => $priority
                );
            }
        }
    }

    /**
     * @param string $modelName
     * @param CDbCriteria $criteria
     * @param array $tpl
     * @param string $frequency
     * @param string $priority
     * @return array
     */
    protected function createUrlsByModel($modelName, $criteria, $tpl, $frequency, $priority) {
        $urls = array();
        if ($criteria == null) {
            $criteria = new CDbCriteria();
        }
        $model = new $modelName();
        $models = $model->findAll($criteria);
        $route = $tpl[0];
        array_shift($tpl);
        foreach ($models as $model) {
            $params = array();
            foreach ($tpl as $k => $v) {
                $params[$k] = $model->$v;
            }
            $urls[] = array(
                'url' => Yii::app()->createAbsoluteUrl($route, $params),
                'frequency' => $frequency,
                'priority' => $priority
            );
        }
        return $urls;
    }

    /**
     * @param string $url
     * @param string $frequency
     * @param string $priority
     * @return string
     */
    protected function createUrlItem($url, $frequency, $priority, $time = '') {
        if (empty($time)) {
            $time = date('Y-m-d\TH:i:s+00:00');
        }
//        return sprintf($this->urlItemTpl, $this->escape($url), $frequency, $time, $priority);
        return sprintf($this->urlItemTpl, $this->escape($url), $priority);
    }

    //转码
    protected function escape($str) {
        return str_replace(array('&', "'", '"', '>', '<'), array('&amp;', '&apos;', '&quot;', '&gt;', '&lt; '), $str);
    }

    /**
     * 生成站点地图
     *
     * @return int
     */
    public function generate() {
        ob_start();
        echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
        echo '<urlset xmlns="' . $this->xmlns . '">' . "\r\n";
        foreach ($this->_urls as $url) {
            echo $this->createUrlItem($url['url'], $url['frequency'], $url['priority'], $url['time']) . "\r\n";
        }
        echo '</urlset>' . "\r\n";
        $content = ob_get_clean();
        return file_put_contents($this->basePath . '/' . $this->filename, $content);
    }

}
